package net.pimpas.web.tests.operations;

import java.security.MessageDigest;
import java.util.List;

import net.pimpas.operation.exception.OperationException;
import net.pimpas.operation.operation.OperationAnnotation;
import net.pimpas.operation.persistence.operation.OperationPersistenceAbstract;
import net.pimpas.resourcebundle.serviceprovider.ResourceBundleServiceProvider;
import net.pimpas.resourcebundle.serviceprovider.ResourceBundleServiceProviderFactoryImpl;
import net.pimpas.resourcebundle.serviceprovider.ResourceBundleServiceProviderType;
import net.pimpas.security.serviceprovider.auth.login.LoginNameException;
import net.pimpas.security.serviceprovider.auth.login.LoginPasswordException;
import net.pimpas.web.tests.entitys.user.User;

@OperationAnnotation(name="LoginOperation")
public class LoginOperation extends OperationPersistenceAbstract {
	
	private String login;
	private String password;
	
	public void commit() throws OperationException {
		
	}

	public void end() throws OperationException {
		
	}

	public void init(Object... objects) throws OperationException {
		this.setLogin((String) objects[0]);
		this.setPassword(new String((char[]) objects[1]));
	}

	public void rollBack() throws OperationException {
		
	}

	public void start() throws OperationException {
		
	}

	public Object call() throws Exception {
		List t = super.getSession().createQuery("from User where login = :userLogin").
		setString("userLogin", this.getLogin()).list();
		ResourceBundleServiceProvider bundle = 
			ResourceBundleServiceProviderFactoryImpl.getResourceBundleServiceProvider();
		if(t.size() > 0) {
			// check password
			MessageDigest md = MessageDigest.getInstance("MD5");
			User user = (User) t.get(0);
			String pass = new String(md.digest(this.getPassword().getBytes()));
			if(user.getPassword().equals(pass))
				return user;
			throw new LoginPasswordException(bundle.getMessage(this.getClass(), "userWrongPass",
					ResourceBundleServiceProviderType.INFO, this.getLogin()));
		}
		
		throw new LoginNameException(bundle.getMessage(this.getClass(), "userWrongLogin",
				ResourceBundleServiceProviderType.INFO, this.getLogin()));
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}